package com.douyin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.douyin.entity.Favorites;
import com.douyin.entity.User;
import com.douyin.exception.BaseException;
import com.douyin.holder.UserHolder;
import com.douyin.service.IFavoritesService;
import com.douyin.service.IUserService;
import com.douyin.service.InterestPushService;
import com.douyin.utils.R;
import com.douyin.dto.UpdateUserDTO;
import com.douyin.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/douyin/customer")
@Slf4j
public class CustomerController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IFavoritesService favoritesService;
    @Autowired
    private InterestPushService interestPushService;
    @GetMapping("/getInfo/{userId}")
    public R getInfo(@PathVariable String userId) {
        System.out.println("获取用户信息：" + userId);
        UserVO userVO = userService.getUserInfo(userId);
        return R.ok().data(userVO);
   }
    @GetMapping("/getInfo/")
    public R getDefaultInfo(){
        return R.ok().data(userService.getUserInfo(UserHolder.get().toString()));
    }

    @PutMapping
    public R updareInfo(@RequestBody UpdateUserDTO updateUserDTO){
        System.out.println("更新用户信息：" + updateUserDTO.toString());
        updateUserDTO.setUserId(UserHolder.get());
        userService.updateInfo(updateUserDTO);
        return R.ok();
    }

    @PostMapping("/follows")
    public R follows(@RequestParam Long followsUserId){
        log.info("关注用户："+followsUserId);
        return R.ok().message(userService.follows(followsUserId, UserHolder.get())?"关注成功":"取关成功");
    }

    @GetMapping("/follows")
    public R getFollows(BasePage basePage,Long userId){
        return R.ok().data(userService.getFollows(basePage,userId));
    }

    @GetMapping("/fans")
    public R getFans(BasePage basePage,Long userId){
        return R.ok().data(userService.getFans(basePage,userId));
    }


    //收藏夹
    @GetMapping("/favorites")
    public R getFavorites(){
        return R.ok().data(favoritesService.getFavorites(UserHolder.get()));
    }

    @GetMapping("/favorites/{id}")
    private R getFavoritesById(@PathVariable Long id){
        Long userId = UserHolder.get();
        return R.ok().data(favoritesService.getOne(
                new LambdaQueryWrapper<Favorites>().eq(Favorites::getId,id).eq(Favorites::getUserId,userId)));
    }

    @PostMapping("/favorites")
    public R saveOrUpdateFavorites(@RequestBody @Validated Favorites favorites){
        Long id = favorites.getId();
        Long userId = UserHolder.get();
        favorites.setUserId(userId);
        try{
            favoritesService.saveOrUpdate(favorites);
        }catch (Exception e){
            return R.error().message("收藏夹名字不可重复");
        }
        return R.ok().message(id==null?"收藏成功":"更新成功");
    }

    @DeleteMapping("/favorites/{id}")
    public R deleteFavorites(@PathVariable Long id){
        favoritesService.remove(id,UserHolder.get());
        return R.ok().message("删除成功");
    }

    @PostMapping("/subscribe")
    public R subscribe(@RequestParam(required = false) String types){
        final HashSet<Long> typeSet = new HashSet<>();
        String msg = "取消订阅";
        if (!ObjectUtils.isEmpty(types)){
            for (String s : types.split(",")) {
                typeSet.add(Long.parseLong(s));
            }
            msg = "订阅成功";
        }
        userService.subscribe(typeSet,UserHolder.get());
        return R.ok().message(msg);
    }

    @GetMapping("/subscribe")
    public R listSubscribeType(){
        return R.ok().data(userService.listSubscribeType(UserHolder.get()));
    }

    @GetMapping("/noSubscribe")
    public R listNoSubscribeType(){
        return R.ok().data(userService.listNoSubscribeType(UserHolder.get()));
    }

    @PostMapping("/updateUserModel")
    public R updateUserModel(@RequestBody Map<String, Object> rawData){
        final String labels = rawData.get("labels").toString();
        List<String> labelLit =new ArrayList<>();
        for (String s : labels.split(",")) {
            labelLit.add(s);
        }
        Double score = Double.parseDouble(rawData.get("score").toString());
        if (score == -0.5 || score == 1.0){
            final UserModel userModel = UserModel.buildUserModel(
                    labelLit, Long.parseLong(rawData.get("id").toString()), score);
            interestPushService.updateUserModel(userModel);
        }
        return R.ok();
    }

}
